package org.way.file.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.way.file.config.FileProperties;
import org.way.file.entity.FileEntity;

import javax.annotation.Resource;
import java.io.File;

@Component
@Slf4j
public class FileComponent {

    @Resource
    private FileProperties fileProperties;

    public FileEntity uploadFile(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        FileUtil.mkdir(fileProperties.getUploadPath() + suffix);

        String dateDir = DateUtil.format(DateUtil.date(), "yyyyMMdd");
        FileUtil.mkdir(fileProperties.getUploadPath() + suffix + "/" + dateDir);

        String newFileName = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmssSSS") +
                RandomUtil.randomNumbers(6) + "." + suffix;
        String filePath = fileProperties.getUploadPath() + suffix + "/" + dateDir + "/" + newFileName;
        File newFile = new File(filePath);
        try {
            file.transferTo(newFile);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new RuntimeException("上传文件失败");
        }
        log.info("上传文件成功");

        String url = fileProperties.getDomain() + "/" + fileProperties.getResource() + "/" + suffix + "/" + dateDir + "/" + newFileName;
        FileEntity entity = new FileEntity();
        entity.setUrl(url);
        entity.setFileName(newFileName);
        return entity;
    }
}
